package com.usian.gateway.filter;

import com.usian.common.dtos.Payload;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.util.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Fay
 * @date 2022/7/15&11:37
 */
@Component
public class AuthorizeFilter implements Ordered, GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求
        String path = request.getURI().getPath();
        //如果path中包含/login/login_auth说明是登录请求直接放行
        if (path.contains("/login/login_auth")){
            //直接放行
            return chain.filter(exchange);
        }
        //从request中获取请求头
        HttpHeaders headers = request.getHeaders();
        //获取请求头中的token
        String token = headers.getFirst("token");
        //如果token=null抛出异常
        if (token==null){
            //返回401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //如果token存在 对token进行校验
        try {
            //判断token是否正确
            Payload payload = JwtUtils.getInfoFromToken(token);
            Integer userId = payload.getUserId();
            //将userId放入请求头中
            ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", userId.toString());
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
            //返回错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }



        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
